﻿#region Copyright (c) 2013-04, Olaf Kober <amarok.projects@gmail.com>
//================================================================================
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.
//================================================================================
#endregion

using System;
using System.Diagnostics;
using System.Globalization;
using System.Threading.Tasks;


namespace Amarok.Agents
{
	/// <summary>
	/// </summary>
	internal sealed class OperationHandler<TMessage, TResult, TProgress> :
		IHandler
		where TMessage : Operation<TResult, TProgress>
	{
		// data
		private IAgent mAgent;


		#region ++ IHandler Interface ++

		/// <summary>
		/// </summary>
		void IHandler.Initialize(IAgent agent)
		{
			mAgent = agent;
		}

		/// <summary>
		/// </summary>
		void IHandler.Invoke(Message message)
		{
			var operation = message as TMessage;

			#region (asserts)
			Debug.Assert(operation != null,
				"Implementation Error: message must be cast-able to TMessage!");
			Debug.Assert(this.Callback != null || this.AsyncCallback != null,
				"Implementation Error: either Callback or AsyncCallback must be set!");
			#endregion

			if (operation.TryAcquire())
			{
				// acquired
				if (operation.CancellationToken.IsCancellationRequested)
				{
					// cancel
					operation.CompleteCanceled();
				}
				else
				{
					// invoke
					if (this.Callback != null)
					{
						_InvokeSync(operation);
					}
					else if (this.AsyncCallback != null)
					{
						_InvokeAsync(operation);
					}
				}
			}
			else
			{
				// already acquired

				#region (tracing)
				{
					Trace.WriteLine(String.Format(CultureInfo.InvariantCulture,
						"*** WARNING: DETECTED MULTIPLE OPERATION HANDLER REGISTERED FOR SAME OPERATION TYPE:" +
						"\r\n  OperationType: {0}",
						operation.GetType()
					));
				}
				#endregion
			}
		}

		#endregion

		#region ++ Public Interface ++

		/// <summary>
		/// </summary>
		public Func<TMessage, TResult> Callback
		{
			get;
			private set;
		}

		/// <summary>
		/// </summary>
		public Func<TMessage, Task<TResult>> AsyncCallback
		{
			get;
			private set;
		}


		/// <summary>
		/// </summary>
		public OperationHandler(Func<TMessage, TResult> callback)
		{
			Verify.NotNull(callback, "callback");
			this.Callback = callback;
		}

		/// <summary>
		/// </summary>
		public OperationHandler(Func<TMessage, Task<TResult>> asyncCallback)
		{
			Verify.NotNull(asyncCallback, "asyncCallback");
			this.AsyncCallback = asyncCallback;
		}

		#endregion

		#region Implementation

		private void _InvokeSync(TMessage operation)
		{
			try
			{
				#region (hook: started)
				AgentHooks.RaiseOperationHandlerStarted(mAgent, operation, this.Callback);
				#endregion

				// call handler method
				var result = this.Callback(operation);

				// success
				operation.Complete(result);
			}
			catch (OperationCanceledException)
			{
				// canceled
				operation.CompleteCanceled();
			}
			catch (Exception exception)
			{
				// failure
				operation.CompleteFaulted(exception);

				#region (hook: failed)
				AgentHooks.RaiseOperationHandlerFailed(mAgent, operation, this.Callback, exception);
				#endregion
			}
			finally
			{
				#region (hook: finished)
				AgentHooks.RaiseOperationHandlerFinished(mAgent, operation, this.Callback);
				#endregion
			}
		}

		private void _InvokeAsync(TMessage operation)
		{
			#region (hook: started)
			AgentHooks.RaiseOperationHandlerStarted(mAgent, operation, this.AsyncCallback);
			#endregion

			// call handler method
			this.AsyncCallback(operation)
				.ContinueWith(task =>
				{
					if (task.IsCanceled)
					{
						// canceled
						operation.CompleteCanceled();
					}
					else if (task.IsFaulted)
					{
						// failure
						operation.CompleteFaulted(task.Exception.InnerException);

						#region (hook: failed)
						AgentHooks.RaiseOperationHandlerFailed(mAgent, operation, this.AsyncCallback, task.Exception.InnerException);
						#endregion
					}
					else
					{
						// success
						operation.Complete(task.Result);
					}

					#region (hook: finished)
					AgentHooks.RaiseOperationHandlerFinished(mAgent, operation, this.AsyncCallback);
					#endregion
				},
				TaskContinuationOptions.ExecuteSynchronously);
		}

		#endregion

	}
}
